#!/usr/bin/env bash
# ... if sh is not enough

#
# comment here
#

# "$@" = "$1" "$2" "$3" ... "$n"
# "$*" = "$1y$2y$3y...$n", where y is the value of IFS variable i.e. 
# "$*" is one long string and $IFS act as an separator or token delimiters.
# Use Uppercase Names for ENVIRONMENT Variables and Lowercase for Custom Variables

# IFS='\n\t' # Default IFS for “zsh” is: $' \n\t\0'.

set -euo pipefail
# set -o xtrace

declare -r script_path="${BASH_SOURCE[0]}"
# declare -r script_dir="${script_path%/*}"
declare -r script_file="${script_path##*/}"

# path="dir/basename.ext"
# dir="${path%/*}"
# filename="${path##*/}" # basename.ext
# basename="${path%\.*}"
# ext=${path##*.}


info() { printf "\\e[1m\\e[38;5;14m✔ %s\\e[0m\\n" "$@"; }
warn() { printf "\\e[1m\\e[38;5;148m➜️ %s\\e[0m\\n" "$@"; }
error(){ printf "\\e[1m\\e[38;5;196m✖ %s\\e[0m\\n" "$@"; }

die() {
    local last_error=$?
    if [[ $1 =~ ^[0-9]+$ ]]; then
        last_error=$1
        shift
    fi
    error "${script_file}:${BASH_LINENO[0]} ${FUNCNAME[1]}(${last_error})>$*" >&2
    exit "$last_error"
}

#declare -i # for integer
#declare -a # for array
#declare -r # readonly

if [[ $# -lt 1 ]]; then
    echo "Usage:${script_file} jar-file [target-dir]"
    exit 1
fi

main(){
    jar_file="$1"
    target_dir="${2:-${jar_file%\.*}}"
    # echo "$target_dir"
    
    java -jar fernflower.jar -dgs=true "$jar_file" "$target_dir" || die "failed"
    cd "$target_dir" || die "$target_dir not exist"
    jar xf "$jar_file"  || die "$jar_file not exist"
    cd ../
}

main "$@"